package com.lp.article.listener;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lp.article.mapper.ArticleStatMapper;
import com.lp.article.service.impl.CommentService;
import com.lp.model.constants.CountType;
import com.lp.model.constants.MQConstants;
import com.lp.model.constants.RedisConstants;
import com.lp.model.entity.article.redis.CommentsMsg;
import com.lp.model.entity.article.redis.vo.CommentsMsgVO;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;

@Slf4j
@Component
public class CommentListener {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private ArticleStatMapper articleStatMapper;

    @Autowired
    private CommentService commentService;

    @SneakyThrows
    @RabbitListener(queues = MQConstants.COMMENT_INCR_OR_DECR_QUEUE)
    public void commentIncrMsg(String msg) {
        log.info("MQ 评论增加消息: {}", msg);
        //1.解析数据
        HashMap hashMap = objectMapper.readValue(msg, HashMap.class);
        String type = objectMapper.convertValue(hashMap.get("type"),
                new TypeReference<String>() {});
        Long articleId = objectMapper.convertValue(hashMap.get("articleId"),
                new TypeReference<Long>() {});
        //2.判断是增加还是减少
        int ans = type.equals(CountType.INCR) ? 1 : -1;
        //3.数据库评论量 +1 或 -1
        articleStatMapper.commentIncrOrDecr(articleId, ans);
        //4.redis 评论量 +1 或 -1
        if(Boolean.FALSE.equals(redisTemplate.hasKey(RedisConstants.ARTICLE_COMMENT + articleId))) {
            //1) redis 上不存在，就从数据库同步
            Integer commentCount = articleStatMapper.selectStatByArticleId(articleId).getCommentCount();
            redisTemplate.opsForValue().set(RedisConstants.ARTICLE_COMMENT + articleId, commentCount.toString());
        } else {
            //2) 存在就 +1 或 -1
            redisTemplate.opsForValue().increment(RedisConstants.ARTICLE_COMMENT + articleId, ans);
        }
        //5.发布新评论的消息
        if(ans == 1) {
            commentService.addMsg(new CommentsMsg(articleId));
        }
        log.info("MQ 评论量同步成功");
    }

}
